import Editor, { useMonaco } from '@monaco-editor/react';
type MonacoEditor = typeof import('monaco-editor')

import useCodeStore from '@/store/code';

import { useEffect, useState } from 'react'
import { useDebounce } from 'usehooks-ts'

export default function CodeEditor() {
  const store = useCodeStore()

  const monaco = useMonaco();
  useEffect(() => {
    if (monaco) {
      store.initMonaco(monaco)
    }
  }, [monaco]);

  function handleEditorWillMount(monaco: MonacoEditor) {
    // here is the monaco instance
    // do something before editor is mounted
    monaco.editor.getModels()[0].setEOL(monaco.editor.EndOfLineSequence.LF)
  }

  const [value, setValue] = useState<string>('')
  const debouncedValue = useDebounce<string>(value, 500)
  useEffect(() => {
    store.onEditorChange(debouncedValue)
  }, [debouncedValue])

  return (
    <div style={{ height: 'unset' }}>
      <Editor
        height="calc(100vh - 80px)"
        defaultLanguage="javascript"
        defaultValue=""
        beforeMount={handleEditorWillMount}
        onChange={v => { if (v) setValue(v) }}
      />
    </div>
  )
}
